﻿using Inaction.ServiceContract;
using Inaction.Rule;
using Inaction.Security;
using Inaction.Util;
using System;
using System.Runtime.Serialization;

namespace Inaction.ServiceProxy
{
    [Serializable]
    [DataContract]
    public class Request
    {
        #region 属性
        SerializeType serializerType;
        [DataMember]
        public SerializeType SerializerType
        {
            get { return serializerType; }
            set { serializerType = value; }
        }

        private byte[] _objData = null;
        [DataMember]
        public byte[] ObjData
        {
            get { return _objData; }
            set { _objData = value; }
        }

        [NonSerialized]
        object obj = null;

        bool isCompressed = false;
        [DataMember]
        public bool IsCompressed
        {
            get { return isCompressed; }
            set { isCompressed = value; }
        }

        public RequestData RequestData
        {
            get { return GetObject<RequestData>(); }
        }

        #endregion

        #region 构造
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
        public Request()
        {
        }

        public Request(RequestData obj, bool needCompress = true)
            : this()
        {
            if (needCompress && !IsCompressed)
            {
                this.ObjData = ServiceContainer.GetService<ISerializerHelper>().DefaultSerializer.Serialize(obj);
                this.ObjData = ServiceContainer.GetService<IZip>().Compress(this.ObjData);
                SerializerType = ServiceContainer.GetService<ISerializerHelper>().DefaultSerializer.SerializeType;
                IsCompressed = true;
            }
            else
            {
                this.obj = obj;
            }
        }

        #endregion

        #region 方法
        public T GetObject<T>() where T : class
        {
            if (obj != null)
            {
                return (T)obj;
            }
            if (IsCompressed)
            {
                ObjData = ServiceContainer.GetService<IZip>().Decompress(ObjData);
            }
            if (ObjData != null)
            {
                obj = ServiceContainer.GetService<ISerializerHelper>().DefaultSerializer.Deserialize<T>(ObjData);
            }
            return (T)obj;
        }
        #endregion
    }
}
